//
//  KnowLedgeViewController.m
//  SportSocial
//
//  Created by yull on 14/12/24.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "KnowLedgeViewController.h"
#import "NewsContentViewController.h"

#import "NewsBannerView.h"
#import "NewsNet.h"
#import "TopNewsCell.h"
#import "CommonNewsCell.h"
#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshLoadMoreContainView.h"

#define KnowLedge_Page_Size 10

@interface KnowLedgeViewController ()<UITableViewDataSource,UITableViewDelegate,NewsBannerViewDelegate>

@property (nonatomic, strong) NewsBannerView *bannerView;

@property (nonatomic, strong) NSArray *arrayTopKnowLedge;
@property (nonatomic, strong) NSMutableArray *arrayKnowLedge;

@property (nonatomic, assign) NSInteger currentKnowLedgePage;
@property (nonatomic, assign) NSInteger maxKnowLedgePage;
@property (nonatomic, copy)   NSString *KnowLedgeKey;

@end

@implementation KnowLedgeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initTableView];
    
    CGRect rect = CGRectMake(0, 0, self.tableViewKnowLedge.width, 250);
    self.bannerView = [[NewsBannerView alloc] initWithFrame:rect];
    self.bannerView.delegate = self;
    self.tableViewKnowLedge.tableHeaderView = self.bannerView;
    
    [self loadTopKnowLedgeFromServer];
    
    [self loadCommonKnowLedgeFromServer];
}

- (void)initTableView
{
    self.tableViewKnowLedge = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableViewKnowLedge.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.tableViewKnowLedge.delegate = self;
    self.tableViewKnowLedge.dataSource = self;
    self.tableViewKnowLedge.backgroundColor = [UIColor clearColor];
    self.tableViewKnowLedge.tableFooterView = [UIView new];
    [self.view addSubview:self.tableViewKnowLedge];
    
    @weakify(self);
    [self.tableViewKnowLedge nd_addPullToRefreshWithActionHandler:^(id sender) {
        @strongify(self);
        self.currentKnowLedgePage = 0;
        [self loadTopKnowLedgeFromServer];
        [self loadCommonKnowLedgeFromServer];
    } loadMoreWithActionHandler:^(id sender) {
        @strongify(self);
        [self loadCommonKnowLedgeFromServer];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayKnowLedge.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == -1) {
        static NSString *topIdentifier = @"TopNews";
        TopNewsCell *topNewsCell = [tableView dequeueReusableCellWithIdentifier:topIdentifier];
        if (!topNewsCell) {
            topNewsCell = [[TopNewsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:topIdentifier];
        }
        return topNewsCell;
    }else {
        static NSString *commonIdentifier = @"CommonNews";
        CommonNewsCell *commonNewsCell = [tableView dequeueReusableCellWithIdentifier:commonIdentifier];
        if (!commonNewsCell) {
            commonNewsCell = [[CommonNewsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:commonIdentifier];
        }
        [commonNewsCell drawCellWithNewsModel:[self.arrayKnowLedge objectAtIndex:indexPath.row]];
        return commonNewsCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == -1) {
        return [TopNewsCell defaultTopNewsCellHeight];
    }
    return [CommonNewsCell defaultCommonNewsCellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel *news = [self.arrayKnowLedge objectAtIndex:indexPath.row];
    [self pushToNewsContentWithNews:news];
}

#pragma mark KnowLedge
- (void)loadTopKnowLedgeFromServer
{
    [NewsNet getTopKnowLedgeWithSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *array = [responseObject objectForKey:@"data"];
            self.arrayTopKnowLedge = [NewsModel newsArrayWithDictArray:array];
            
            dispatch_async(dispatch_get_main_queue(), ^{
               self.bannerView.newsArray = self.arrayTopKnowLedge;
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)loadCommonKnowLedgeFromServer
{
    if (!self.arrayKnowLedge) {
        self.arrayKnowLedge = [NSMutableArray array];
    }
    
    [NewsNet paginateKnowLedgeWithPageNumber:self.currentKnowLedgePage+1 pageSize:KnowLedge_Page_Size successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            
            if (self.currentKnowLedgePage == 0) {
                [self.arrayKnowLedge removeAllObjects];
            }
            
            NSArray *dictArray = [[[responseObject objectForKey:@"data"] objectForKey:@"page"] objectForKey:@"list"];
            
            self.knowLedgeKey = [[responseObject objectForKey:@"data"] objectForKey:@"rkey"];
            self.currentKnowLedgePage = [[[[responseObject objectForKey:@"data"] objectForKey:@"page"] objectForKey:@"pageNumber"] integerValue];
            self.maxKnowLedgePage = [[[[responseObject objectForKey:@"data"] objectForKey:@"page"] objectForKey:@"totalPage"] integerValue];
            
            [self.arrayKnowLedge addObjectsFromArray:[NewsModel newsArrayWithDictArray:dictArray]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentKnowLedgePage == self.maxKnowLedgePage) {
                    ((NDRefreshLoadMoreContentView *)(self.tableViewKnowLedge.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                } else {
                    ((NDRefreshLoadMoreContentView *)(self.tableViewKnowLedge.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                }
                [self.tableViewKnowLedge reloadData];
                [self endLoad];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
                [self endLoad];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
            [self endLoad];
        });
    }];
}

- (void)endLoad
{
    [self.tableViewKnowLedge nd_endLoadMore];
    [self.tableViewKnowLedge nd_endRefreshing];
}

#pragma mark - 跳转
- (void)pushToNewsContentWithNews:(NewsModel *)news
{
    NewsContentViewController *contentViewController = [[NewsContentViewController alloc] initWithNews:news];
    contentViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:contentViewController animated:YES];
}

#pragma mark - NewsBannerViewDelegate
- (void)newsBannerViewClickAtIndex:(NSInteger)index
{
    NewsModel *news = [self.arrayTopKnowLedge objectAtIndex:index];
    [self pushToNewsContentWithNews:news];
}
@end
